package com.yuyu.util;

import org.apache.commons.lang3.StringUtils;

/**
 * 类型转换工具类
 *
 * @author yuyu
 * @date 2018/10/19
 */
public  class CastUtil {

    public static String castString(Object o) {
        return CastUtil.castString(o, "");
    }

    public static String castString(Object o, String defaultValue) {
        return o != null ? String.valueOf(o) : defaultValue;
    }

    public static double castDubbo(Object o) {
        return CastUtil.castDubbo(o, 0);
    }

    public static double castDubbo(Object o, double defaultValue) {
        double value = defaultValue;
        if (o != null) {
            String strValue = castString(o);
            if (StringUtils.isNotEmpty(strValue)) {
                try {
                    value = Double.parseDouble(strValue);
                } catch (NumberFormatException e) {
                    value = defaultValue;
                }
            }
        }
        return value;
    }



    public static long castLong(Object o) {
        return CastUtil.castLong(o, 0);
    }

    public static long castLong(Object o, long defaultValue) {
        long value = defaultValue;
        if (o != null) {
            String strValue = castString(o);
            if (StringUtils.isNotEmpty(strValue)) {
                try {
                    value = Long.parseLong(strValue);
                } catch (NumberFormatException e) {
                    value = defaultValue;
                }
            }
        }
        return value;
    }



    public static int castInt(Object o) {
        return CastUtil.castInt(o, 0);
    }

    public static int castInt(Object o, int defaultValue) {
        int value = defaultValue;
        if (o != null) {
            String strValue = castString(o);
            if (StringUtils.isNotEmpty(strValue)) {
                try {
                    value = Integer.parseInt(strValue);
                } catch (NumberFormatException e) {
                    value = defaultValue;
                }
            }
        }
        return value;
    }


    public static boolean castBoolean(Object o) {
        return CastUtil.castBoolean(o, false);
    }

    public static boolean castBoolean(Object o, boolean defaultValue) {
        boolean value = defaultValue;
        if (o != null){
            value = Boolean.parseBoolean(castString(o));
        }
        return value;
    }
}
